/**
 * 
 */
package zeroj.orm.ibatis;

import java.io.Serializable;
import java.sql.SQLException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import zeroj.orm.DaoException;

import com.ibatis.sqlmap.client.SqlMapSession;

/**
 * @author lyl
 *
 * @since 1.0
 * 
 * 2008-9-12
 */
public abstract class IBatisTemplate<T> {

	private static final Log log = LogFactory.getLog(IBatisTemplate.class);
	
	protected SqlMapSession getSession() throws DaoException {
		
		return IbatisSupport.currentSession();
	}
	
	protected int delete(String stmt, Serializable pk) throws DaoException {
		
		try {
			return getSession().delete(stmt, pk);
		} catch(SQLException sqle) {
			log.warn("delete failed by pk " + pk, sqle);
			throw new DaoException("delete failed", sqle);
		}
	}
	protected Object queryForObject(String stmt, Object param) throws DaoException {
		
		try {
			return getSession().queryForObject(stmt, param);
		} catch(SQLException sqle) {
			log.warn("query for object " + stmt, sqle);
			throw new DaoException("query for object failed", sqle);
		}
	}
	protected Object insert(String stmt, T object) throws DaoException {
		
		try {
			return getSession().insert(stmt, object);
		}  catch(SQLException sqle) {
			log.warn("insert " + object, sqle);
			throw new DaoException("insert failed", sqle);
		}
	}
	
	protected int update(String stmt, T object) throws DaoException {
		
		try {
			return getSession().update(stmt, object);
		} catch(SQLException sqle) {
			log.warn("update " + object, sqle);
			throw new DaoException("update failed", sqle);
		}
	}
	protected int delete(String stmt) throws DaoException {
		
		try {
			return getSession().delete(stmt);
		} catch (SQLException e) {
			log.warn("delete " + stmt, e);
			throw new DaoException("delete failed", e);
		}
	}
}
